package com.yangtzeu.jwc.activity;

import com.yangtzeu.jwc.business.AppBusiness;
import com.yangtzeu.jwc.business.MCallBack;
import com.yangtzeu.jwc.business.UpdateBusiness;
import com.yangtzeu.jwc.business.UpdateListener;
import com.yangtzeu.jwc.domain.MyJson;
import com.yangtzeu.jwc.domain.ServerConfig;
import com.yangtzeu.jwc.domain.Student;
import com.yangtzeu.jwc.fragment.IndexFragment;
import com.yangtzeu.jwc.fragment.LeftFragment;
import com.yangtzeu.jwc.fragment.MoreFragment;
import com.yangtzeu.jwc.fragment.ScoreFragment;
import com.yangtzeu.jwc.fragment.TimetableFragment;
import com.yangtzeu.jwc.fragment.UserFragment;
import com.yangtzeu.jwc.utils.AllActivitys;
import com.yangtzeu.jwc.utils.ConfirmDialog;
import com.yangtzeu.jwc.utils.G;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.DataUtil;
import com.zjsx.lib.utils.L;
import com.zjsx.lib.utils.PrefUtil;
import com.zjsx.lib.utils.T;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import java.util.Date;

public class MainActivity extends BaseActivity implements OnCheckedChangeListener, UpdateListener {
    DrawerLayout mDrawerLayout;
    RelativeLayout mainContent;
    RelativeLayout mainLeft;
    ActionBarDrawerToggle mDrawerToggle;
    public static Student student;
    FragmentManager fragmentManager;

    Fragment main;
    Fragment left;
    Fragment right;
    private Fragment index_fragment, score_fragment, timetable_fragment, user_fragment, more_fragment;

    private ServerConfig sc;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentManager = getFragmentManager();
        switchTab(R.id.home, true);
        // UpdateBusiness ab = new UpdateBusiness(this);
        // ab.update(null);
        config();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return false;
    }

    @Override
    public void setView() {
        // TODO Auto-generated method stub
        super.setView();
        setContentView(R.layout.activity_main2);
    }

    @Override
    public void initData() {
        // TODO Auto-generated method stub
        super.initData();
    }

    @Override
    public void initActionBar() {
        // TODO Auto-generated method stub
        super.initActionBar();
    }

    @Override
    public void initView() {
        // TODO Auto-generated method stub
        super.initView();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer_layout);
        mainContent = (RelativeLayout) findViewById(R.id.main_content);
        mainLeft = (RelativeLayout) findViewById(R.id.main_left);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // TODO Auto-generated method stub
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // TODO Auto-generated method stub
                super.onDrawerOpened(drawerView);
            }

        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        left = new LeftFragment(this);

        // getFragmentManager().beginTransaction().add(R.id.main_content,
        // main).commit();
        getFragmentManager().beginTransaction().add(R.id.main_left, left).commit();

    }

    @Override
    public void initListener() {
        // TODO Auto-generated method stub
        super.initListener();
    }

    @Override
    public void initAdapter() {
        // TODO Auto-generated method stub
        super.initAdapter();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        super.onClick(v);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    public void setTab(Fragment fragment, boolean isChecked, boolean isAdd) {
        L.d("MainActivity--->" + "isChecked" + isChecked + "isAdd=" + isAdd);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (isAdd) {
            transaction.add(R.id.main_content, fragment);
        } else {
            if (isChecked) {
                transaction.show(fragment);
                // 调用一下isHidden,通知fragment被显示了.
                fragment.isHidden();
            } else {
                transaction.hide(fragment);
            }
        }
        transaction.commit();
    }

    public void switchTab(int id, boolean isChecked) {
        // TODO Auto-generated method stub
        boolean isAdd = false;
        switch (id) {
            case R.id.home:
                if (index_fragment == null) {
                    index_fragment = new IndexFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(index_fragment, isChecked, isAdd);
                break;
            case R.id.score:
                if (score_fragment == null) {
                    score_fragment = new ScoreFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(score_fragment, isChecked, isAdd);
                break;
            case R.id.timetable:
                if (timetable_fragment == null) {
                    timetable_fragment = new TimetableFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(timetable_fragment, isChecked, isAdd);
                break;
            case R.id.user:
                if (user_fragment == null) {
                    user_fragment = new UserFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(user_fragment, isChecked, isAdd);
                break;
            case R.id.more:
                if (more_fragment == null) {
                    more_fragment = new MoreFragment();
                    isAdd = true;
                } else {
                    isAdd = false;
                }
                setTab(more_fragment, isChecked, isAdd);
                break;
            default:
                break;
        }
    }

    public void config() {
        if (!PrefUtil.getBoolean(G.IS_INFO_UPLOADED, false)) {
            install();
        } else {
            server();
        }
    }

    private void install() {
        AppBusiness ab = new AppBusiness(this);
        ab.install(new MCallBack() {
            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, MyJson mj) {
                sc = DataUtil.dataToObj(mj.data, ServerConfig.class);
                onConfig();
            }
        });
    }

    private void server() {
        AppBusiness ab = new AppBusiness(this);
        ab.server(new MCallBack() {
            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, MyJson mj) {
                sc = DataUtil.dataToObj(mj.data, ServerConfig.class);
                onConfig();
                L.d(sc.toString());
            }

        });
    }

    private void onConfig() {
        if (sc.close) {
            //此App不在维护
            ConfirmDialog.show(this, "通知", sc.message);
            AllActivitys.getInstance().exit();

        }else if(sc.message!=null){
            ConfirmDialog.show(this, "通知", sc.message);
        }
        UpdateBusiness ub = new UpdateBusiness(MainActivity.this, MainActivity.this);
        if (ub.checkVersion(sc.version)) {
            ub.haveNewVersion(sc.version);
        }
    }

    @Override
    public void cancelUpdate() {
        // TODO Auto-generated method stub
        if (sc.version.forceUpdate == 1) {
            AllActivitys.getInstance().exit();
        }
    }

    @Override
    public void cancelDownload() {
        // TODO Auto-generated method stub
        if (sc.version.forceUpdate == 1) {
            AllActivitys.getInstance().exit();
        }
    }

    @Override
    public void cancelDownloadFromExplorer() {
        // TODO Auto-generated method stub
        if (sc.version.forceUpdate == 1) {
            AllActivitys.getInstance().exit();
        }
    }

    @Override
    public void downloadFromExplorer() {
        // TODO Auto-generated method stub
        AllActivitys.getInstance().exit();
    }

    int hideId;
    int showId;

    @Override
    public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
        // TODO Auto-generated method stub
        L.d("MainActivity--->Tab changed!");
        if (isChecked) {
            showId = buttonView.getId();

            mDrawerLayout.setDrawerListener(new DrawerListener() {

                @Override
                public void onDrawerStateChanged(int arg0) {
                    // TODO Auto-generated method stub
                    mDrawerToggle.onDrawerStateChanged(arg0);
                }

                @Override
                public void onDrawerSlide(View arg0, float arg1) {
                    // TODO Auto-generated method stub
                    mDrawerToggle.onDrawerSlide(arg0, arg1);
                }

                @Override
                public void onDrawerOpened(View arg0) {
                    // TODO Auto-generated method stub
                    mDrawerToggle.onDrawerOpened(arg0);
                }

                @Override
                public void onDrawerClosed(View arg0) {
                    // TODO Auto-generated method stub
                    mDrawerToggle.onDrawerClosed(arg0);
                    switchTab(hideId, false);
                    switchTab(buttonView.getId(), isChecked);
                }
            });
            mDrawerLayout.closeDrawer(Gravity.START);
        } else {
            hideId = buttonView.getId();
        }
    }

    // 复写点击返回的事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit(new Date());
        }
        return false;
    }

    // 控制0.5秒以内连点击两次返回才能退出
    // 记录上一次点击的时间
    private Date date = new Date();

    private void exit(Date date) {

        if ((date.getTime() - this.date.getTime()) < (1 * 1000)) {
            date = null;
            AllActivitys.getInstance().exit();
        } else {
            Toast.makeText(getApplicationContext(), "再按一次退出程序!", Toast.LENGTH_SHORT).show();
            this.date = date;
        }
    }
}
